import { DATE_FOMRAT } from '@/constants';
import {
  DatePicker,
  DatePickerView,
  Picker,
  Popup,
  Selector,
  SelectorOption,
  SideBar,
} from 'antd-mobile';
import React, { FC, ReactNode, useEffect, useState } from 'react';

// 以下两种导入方式是不一样的
// const dayjs = require('dayjs');
import dayjs from 'dayjs';

require('dayjs/plugin/quarterOfYear');
dayjs.extend(require('dayjs/plugin/quarterOfYear'));

// import { DemoBlock } from '@/components/demos-util';
import { DownOutline } from 'antd-mobile-icons';
import { PickerDate } from 'antd-mobile/es/components/date-picker/util';
import { PickerValue } from 'antd-mobile/es/components/picker-view';
import classNames from 'classnames';
import styles from './index.less';
declare type ComplexDateSelectedValue = {
  sideBarKey: string;
  preDefine: string;
  year: PickerDate;
  month: PickerDate;
  day: PickerDate;
  minDay: PickerDate;
  maxDay: PickerDate;
  tip: ReactNode;
  lastClick?: string;
};
export const DateDefaultValue = {
  sideBarKey: 'month',
  preDefine: 'currentYear',
  lastClick: undefined,
  year: new Date(),
  month: new Date(),
  day: new Date(),
  minDay: new Date(),
  maxDay: new Date(),
  tip: '不限',
};

export { ComplexDateSelectedValue };

const DateSelectPopup: FC<{
  visable: boolean;
  hide: (x: boolean) => void;
  dateSelectedValue: ComplexDateSelectedValue;
  setDateSelectedValue: (v: ComplexDateSelectedValue) => void;
}> = ({ hide, visable, dateSelectedValue, setDateSelectedValue }) => {
  const { sideBarKey, preDefine, year, month, day, minDay, maxDay } =
    dateSelectedValue;

  return (
    <Popup
      visible={visable}
      onMaskClick={() => {
        hide(false);
      }}
      onClose={() => {
        hide(false);
      }}
      position="bottom"
      bodyStyle={{ height: '50vh', overflowY: 'scroll' }}
    >
      <div className={styles.container}>
        <div className={styles.side}>
          <SideBar
            defaultActiveKey={sideBarKey}
            activeKey={sideBarKey}
            onChange={(key: string) => {
              setDateSelectedValue({
                ...dateSelectedValue,
                sideBarKey: key,
              });
            }}
          >
            {[
              {
                title: '常用',
                key: 'preDefine',
              },
              {
                key: 'year',
                title: '按年',
                badge: '5',
              },
              {
                key: 'month',
                title: '按月',
                badge: '5',
              },
              {
                key: 'day',
                title: '按日',
                badge: '5',
              },
              {
                key: 'dayRange',
                title: '时间段',
                badge: '99+',
                disabled: true,
              },
            ].map((item) => (
              <SideBar.Item key={item.key} title={item.title} />
            ))}
          </SideBar>
        </div>
        <div className={styles.main}>
          <div
            className={classNames(
              styles.content,
              sideBarKey === 'preDefine' && styles.active,
            )}
          >
            <Selector
              options={[
                { value: 'today', label: '今日' },
                { value: 'yesterday', label: '昨天' },
                { value: 'last7Days', label: '近7天' },
                
                { value: 'currentYear', label: '本年' },
                { value: 'currentMonth', label: '本月' },
                { value: 'currentWeek', label: '本周' },
                { value: 'lastYear', label: '上年' },
                { value: 'lastMonth', label: '上月' },
                { value: 'lastWeek', label: '上周' },
                
              ]}
              defaultValue={[preDefine]}
              columns={3}
              value={[preDefine]}
              onChange={(
                arr: string[],
                { items }: { items: SelectorOption<string>[] },
              ) => {
                console.log(arr, items);
                setDateSelectedValue({
                  ...dateSelectedValue,
                  preDefine: arr[0],
                  lastClick: 'preDefine',
                  tip: items[0].label!,
                });
              }}
            />
          </div>
          <div
            className={classNames(
              styles.content,
              dateSelectedValue.sideBarKey === 'year' && styles.active,
            )}
          >
            <DatePickerView
              precision="year"
              max={new Date()}
              defaultValue={year}
              value={year}
              onChange={(value: PickerDate) => {
                setDateSelectedValue({
                  ...dateSelectedValue,
                  year: value,
                  lastClick: 'year',
                  tip: value.getFullYear(),
                });
              }}
            />
          </div>
          <div
            className={classNames(
              styles.content,
              dateSelectedValue.sideBarKey === 'month' && styles.active,
            )}
          >
            <DatePickerView
              precision="month"
              max={new Date()}
              defaultValue={month}
              value={month}
              onChange={(value: PickerDate) => {
                setDateSelectedValue({
                  ...dateSelectedValue,
                  month: value,
                  lastClick: 'month',
                  tip: dayjs(value).format('YY/MM'),
                });
              }}
            />
          </div>
          <div
            className={classNames(
              styles.content,
              dateSelectedValue.sideBarKey === 'day' && styles.active,
            )}
          >
            <DatePickerView
              precision="day"
              max={new Date()}
              defaultValue={day}
              value={day}
              onChange={(value: PickerDate) => {
                setDateSelectedValue({
                  ...dateSelectedValue,
                  day: value,
                  lastClick: 'day',
                  tip: dayjs(value).format('YYYY/MM/DD'),
                });
              }}
            />
          </div>
          <div
            className={classNames(
              styles.content,
              sideBarKey === 'dayRange' && styles.active,
            )}
          >
            <div className={styles.period}>
              <span>开始日期</span>
              <DatePickerView
                precision="day"
                max={new Date()}
                defaultValue={minDay}
                value={minDay}
                onChange={(value: PickerDate) => {
                  setDateSelectedValue({
                    ...dateSelectedValue,
                    minDay: value,
                    lastClick: 'minDay',
                    tip:
                      dayjs(value).format('YY/M/D') +
                      '-' +
                      dayjs(maxDay).format('YY/M/D'),
                  });
                }}
              />
            </div>
            <div className={styles.period}>
              <span>结束日期</span>
              <DatePickerView
                precision="day"
                max={new Date()}
                defaultValue={maxDay}
                value={maxDay}
                onChange={(value: PickerDate) => {
                  setDateSelectedValue({
                    ...dateSelectedValue,
                    maxDay: value,
                    lastClick: 'maxDay',
                    tip:
                      dayjs(minDay).format('YY/M/D') +
                      '-' +
                      dayjs(value).format('YY/M/D'),
                  });
                }}
              />
            </div>
          </div>
        </div>
      </div>
    </Popup>
  );
};

// 2025-01-01将首页产值，新签收款统计的时间选择组件，抽出来放在这里

const DateRangeSelector: FC<{
  period: string;
  initStart?:string
  initEnd?:string,
  onTimeChange: (a: string, b: string,type:string) => void;

}> = ({ period, onTimeChange,initStart,initEnd }) => {
  const [chartTimeVisible, setChartTimeVisible] = useState<boolean>(false);
  const [chartTime, setChartTime] = useState<PickerValue[]>([period]);

  const [startTime, setStartTime] = useState<string>(initStart||'');
  const [endTime, setEndTime] = useState<string>(initEnd||'');

  const [startTimeVisible, setStartTimeVisible] = useState<boolean>(false);
  
  const [endTimeVisible, setEndTimeVisible] = useState<boolean>(false);


  useEffect(() => {
    if (chartTime[0]) {
      let start: string = '',
        end: string = '',
        date = dayjs();
        if (chartTime[0] === 'M') {
          start = date.startOf('month').format(DATE_FOMRAT);
          end = date.endOf('month').format(DATE_FOMRAT);
        } else if (chartTime[0] === 'Q') {
          start = date.startOf('quarter').format(DATE_FOMRAT);
          end = date.endOf('quarter').format(DATE_FOMRAT);
        } else if (chartTime[0] === 'Y') {
          start = date.startOf('year').format(DATE_FOMRAT);
          end = date.endOf('year').format(DATE_FOMRAT);
        } else if (chartTime[0] === 'LM') {
          start = date.startOf('month').subtract(1, 'month').format(DATE_FOMRAT);
          end = date.endOf('month').subtract(1, 'month').format(DATE_FOMRAT);
        } 
        else if (chartTime[0] === 'LY') {
          start = date.startOf('year').subtract(1, 'year').format(DATE_FOMRAT);
          end = date.endOf('year').subtract(1, 'year').format(DATE_FOMRAT);
        } 

        else if (chartTime[0] === 'LQ') {
          start = date
            .startOf('quarter')
            .subtract(1, 'quarter')
            .format(DATE_FOMRAT);
          end = date.endOf('quarter').subtract(1, 'quarter').format(DATE_FOMRAT);
        } else if (chartTime[0] === 'Date' && startTime && endTime) {
          start = startTime;
          end = endTime;
        }
        if (start && end) {
          console.log(`DateRangeSelector, time chage:${start}-${end},type=${chartTime[0]}`);
          onTimeChange(start, end, chartTime[0]+'');
        }
    }
  }, [chartTime, startTime, endTime]);
  const colulmns: { label:string,value:string }[]  = [
    { label: '当月', value: 'M' },
    { label: '当季', value: 'Q' },
    { label: '当年', value: 'Y' },
    { label: '上年', value: 'LY' },
    { label: '上月', value: 'LM' },
    { label: '上季', value: 'LQ' },
    { label: '自定义', value: 'Date' },
  ]

  return (
    <React.Fragment>
      <a onClick={() => setChartTimeVisible(true)}>
        { colulmns.some(c=>c.value === chartTime[0]) &&  colulmns.filter(c=>c.value === chartTime[0])[0].label }
        <DownOutline />
        <Picker
          columns={[ colulmns,]}
          visible={chartTimeVisible}
          onClose={() => {
            setChartTimeVisible(false);
          }}
          value={chartTime}
          onConfirm={(v:PickerValue[]) => {
            setChartTime(v);
          }}
        />
      </a>
      {chartTime[0] === 'Date' && (
        <>
          <a
            onClick={() => setStartTimeVisible(true)}
            style={{ marginLeft: 10 }}
          >
            {startTime ? dayjs(startTime).format('YY-M-D') : '开始时间'}
          </a>
          <DatePicker
            title="开始时间"
            visible={startTimeVisible}
            onClose={() => {
              setStartTimeVisible(false);
            }}
            onConfirm={(val) => {
              setStartTime(dayjs(val).format('YYYY-MM-DD'));
            }}
          />
          &nbsp;-&nbsp;
          <a onClick={() => setEndTimeVisible(true)}>
            {endTime ? dayjs(endTime).format('YY-M-D') : '结束时间'}
          </a>
          <DatePicker
            title="结束时间"
            visible={endTimeVisible}
            onClose={() => {
              setEndTimeVisible(false);
            }}
            onConfirm={(val) => {
              setEndTime(dayjs(val).format('YYYY-MM-DD'));
            }}
          />
        </>
      )}
    </React.Fragment>
  );
};

export { DateRangeSelector };
export default DateSelectPopup;
